package cn.btks.resultintegration.rule.service.impl;

import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.resultintegration.catalog.pojo.Catalog;
import cn.btks.resultintegration.rule.pojo.SubstanceParam;
import cn.btks.resultintegration.rule.repository.SubstanceParamRepository;
import cn.btks.resultintegration.rule.service.SubstanceParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2021/10/15 10:43
 */
@Service
public class SubstanceParamServiceImpl implements SubstanceParamService {

    @Autowired
    SubstanceParamRepository substanceParamRepository;

    @Override
    public SubstanceParam findById(Long id) {
        Optional<SubstanceParam> optional = substanceParamRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<SubstanceParam> findAllByParentId(Long parentId) {
        return substanceParamRepository.findAllByParentId(parentId);
    }

    @Override
    public ResultState save(SubstanceParam substanceParam) {
        SubstanceParam save = substanceParamRepository.save(substanceParam);
        return save != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), save) :
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState update(SubstanceParam substanceParam) {
        if (substanceParam.getId() != null) {
            SubstanceParam update = substanceParamRepository.save(substanceParam);
            return update != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), update) :
                    new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.SAVE_ERROR1.getCode(), StateInfo.SAVE_ERROR1.getMsg());
    }

    @Override
    public ResultState delete(Long id) {
        Optional<SubstanceParam> optional = substanceParamRepository.findById(id);
        if (optional.isPresent()) {
            substanceParamRepository.deleteById(optional.get().getId());
            return new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg());
        }
        return new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
    }
}
